<template>
  <div class='container'>
    <el-card class="tree-card" >
      {{$route.query.id ? '试题修改' : '试题录入'}}
    </el-card>
    <el-card class="tree-card">
      <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
      <el-form-item label="学科:" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择" style="width:400px" >
          <el-option
          v-for="item in subjects"
          :key="item.id"
          :label="item.subjectName"
          :value="item.id"
           ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录:" prop="catalogID" >
      <el-select v-model="form.catalogID" placeholder="请选择" style="width:400px">
        <el-option
        v-for="i in directorys "
        :key='i.id'
         :label="i.directoryName"
         :value="i.id">
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="企业:" prop="enterpriseID" >
      <el-select v-model="form.enterpriseID" placeholder="请选择" style="width:400px">
         <el-option
        v-for="i in companys "
        :key='i.id'
         :label="i.company"
         :value="i.id">
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="城市:" prop="city">
      <el-select v-model="form.province" placeholder="请选择" style="width:200px">
        <el-option v-for="(i,index) in province"
         :key="index"
         :label="i"
         :value="i"
         @click.native="fn(i)">
        </el-option>
      </el-select>
      <el-select v-model="form.city" placeholder="请选择" style="width:200px">
        <el-option v-for="(i,index) in citys"
         :key="index"
         :label="i"
         :value="i"
         >
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="方向:" prop="direction">
      <el-select v-model="form.direction" placeholder="请选择" style="width:400px">
         <el-option
        v-for="(i,index) in direction "
        :key='index'
         :label="i"
         :value="i">
        </el-option>
      </el-select>
      </el-form-item>
       <el-form-item label="题型" prop="questionType">
          <el-radio
       v-model="form.questionType"
          v-for="item in questionType" :key="item.label" :label="item.value+''"  @change="handelChange(item.value)">
                {{item.label}}
          </el-radio>
      </el-form-item>
       <el-form-item label="难度" prop="difficulty">
          <el-radio   v-for="i in difficulty" :key="i.label"  :label="i.value+''"  v-model="form.difficulty" >
            {{ i.label}}
          </el-radio>

      </el-form-item>
       <el-form-item label="题干" prop="question" style="width:80%">
          <quillEditor v-model="form.question" style="height:100%" :options="editorOptions"></quillEditor>
      </el-form-item>
      <el-form-item label="选项" v-if="!isShow">
        <div   v-for="item in form.options"  :key="item.code" class="twoGroup">
          <el-radio   v-if="type==='radio'" :label="true"  v-model="item.isRight" @change="changeRadio(item)"  >
            {{item.code}}
          </el-radio>
        <el-checkbox  v-if="type==='checkout'"  :label="true"  v-model="item.isRight">
          {{item.code}}
        </el-checkbox>
         <el-input v-model='item.title'  style="width:200px;margin-right:'20px'"></el-input>
         <el-upload
              style="margin-left:4px"
              class="avatar-uploader"
              action="#"
              :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
              :show-file-list="false">
              <img v-if="item.img" :src="item.img" class="avatar">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
        </div>
      <el-button type="danger" :disabled='disabled' @click="addButton"> +增加选项和答案</el-button>
      </el-form-item>
      <el-form-item label="解析视频" style="width:400px">
          <el-input v-model="form.videoURL"></el-input>
      </el-form-item>
      <el-form-item label="答案解析" prop="answer">
        <quillEditor v-model="form.answer" style="height:100%" :options="editorOptions"></quillEditor>
      </el-form-item>
      <el-form-item label="题目备注" >
        <el-input
          style="width:400px"
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model.trim="form.remarks">
        </el-input>
      </el-form-item>
      <el-form-item label="试题标签">
      <el-select
        v-model="form.tags"
        placeholder="请选择试题标签"
        multiple
        filterable
        default-first-option
        allow-create
        >
          <el-option
          v-for=" i in tags "
          :key="i.id"
          :label="i.tagName"
          :value="i.tagName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-button v-if="!$route.query.id" type="primary" @click="submit">确认提交</el-button>
      <el-button v-else @click="update" type="success">确认修改</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

import { list } from '@/api/hmmm/subjects'
import { add, update, detail } from '@/api/hmmm/questions'
import { list as directorys } from '@/api/hmmm/directorys'
import { list as companys } from '@/api/hmmm/companys'
import { detail as TagDetail } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      disabled: '', // 按钮显示或隐藏
      type: 'radio',
      questionType, // 题干
      difficulty, // 难度
      isShow: false,
      subjects: [],
      directorys: [],
      companys: [],
      direction,
      list: [],
      tags: [],
      citys: [],
      provinces,
      index: 0,
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{
          required: true, message: '请选择难度', trigger: 'change'
        }],
        question: [{
          required: true, message: '请输入题干', trigger: 'change'
        }]
      }
    }
  },
  created () {
    this.getSubject()
    this.getDirectorys()
    this.getCompanys()
    this.getTags()
    const res = this.provinces()
    this.province = res
    // 题型
    // const ques = this.handelQuestionType()
    // console.log(ques)
    // // .console.log(res)
  },
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.form = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: 0,
          difficulty: 0,
          question: null,
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ],
          videoURL: '', // 解析视频
          answer: '', // 答案解析
          remarks: '', // 题目备注
          tags: '' // 试题标签
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      // data.tags = data.tags.split(',')
      // data.options = data.options.map(item => {
      //   item.isRight = item.isRight === 1
      //   return item0
      // })
      console.log(data)
      this.form = data
      const res = await detail({ subjectID: this.form.subjectID })
      this.directorys = res.data
      const res2 = await TagDetail({ subjectID: this.form.subjectID })
      this.tags = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    async getSubject () {
      const { data } = await list()
      console.log(data.items)
      this.subjects = data.items

      // console.log(this.subjects)
    },
    // 处理目录
    // handelCatlog (value) {
    //   console.log(value)

    // },
    // 目录
    async getDirectorys () {
      const { data } = await directorys()
      // console.log(res)
      this.directorys = data.items
    },
    // 获取企业
    async getCompanys () {
      const { data } = await companys()
      // console.log(data)
      this.companys = data.items
    },
    // 获取试题标签
    async getTags () {
      const { data } = await TagDetail({ id: this.form.subjectID })
      console.log(data)
      this.tags = data.items
    },
    async fn (str) {
      // console.log(citys)
      this.form.city = ''
      const res = await citys(str)
      this.citys = res
      // console.log(res)
    },
    // 题型
    // 简答
    // 添加
    // 选择了题型
    // 选择单选框
    changeRadio (item) {
      // 1. 清除所有的选中
      this.form.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    addButton () {
      const arr = ['E', 'F', 'G', 'H', 'I', 'J', 'k']
      // console.log(this.form.options)
      // this.form.options.forEach()
      // const conut = arr[0]++
      // const res = arr.reduce((total, item, index, arr) => {
      //   total += index.length
      // }, 0)
      // console.log(res)
      // const res = 1
      console.log(this.index)
      this.form.options.push({ code: `${arr[this.index++]}`, title: '', img: '', isRight: '' })
    },
    // arr[0]

    // 提交表单
    async submit () {
      try {
        await this.$refs.formRef.validate()
        // console.log(1)
        const data = { ...this.form }
        console.log(data)
        data.tags = data.tags.join(',')
        await add(data)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      } catch (error) {
        this.$message.warning('请完善表单')
      }
    },
    // 修改表单
    update () {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          const data = { ...this.form }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    handelChange (str) {
      console.log(str)
      if (str === 1) {
        this.type = 'radio'
        this.isShow = false
        this.disabled = true
        this.form.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      } else if (str === 2) {
        this.type = 'checkout'
        this.disabled = false
        this.isShow = false
        this.form.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      } else {
        this.isShow = true
        this.type = 'isShow'
      }
    }
  }
}
</script>

<style scoped lang='sass'>
::v-deep .ql-editor
  height: 150px

.tree-card
  margin: 0px 20px
.twoGroup
 display: flex
 justify-content: start
 align-items: center
.twoGroup .el-radio
  display: block
  // margin-top: 20px

.twoGroup .el-checkbox
  display: block
  margin-right:  30px !important
  // margin-top: 20px
.el-button--danger
  display: block
  margin-top: 20px

.ql-blank
  display: block
  height: 100px !important

// .el-radio is-checked
//   margin-top: 40px
// .ql-container
//    height: 300px
.first
  margin-bottom: 20px

.el-button--primary
  margin-left: 120px
.avatar-uploader
  display: inline-block
  vertical-align: middle
  line-height: 1

.twoGroup ::v-deep .avatar-uploader .el-upload
  border: 1px dashed #d9d9d9
  border-radius: 6px
  cursor: pointer
  position: relative
  width: 100px
  height: 60px
  line-height: 60px

.twoGroup ::v-deep .avatar-uploader .el-upload:hover
  border-color: #409EFF

.twoGroup ::v-deep .avatar-uploader i
  position: absolute
  right: 0
  top: 0
  transform: translate(50%,-50%)
  background: #fff
  font-size: 18px
  color: #999

.avatar
  width: 100px
  height: 60px
  display: block
  overflow: hidden

</style>
